package com.net.oil.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.net.oil.R;
import com.net.oil.app.Constant;
import com.net.oil.app.UserInfoManager;
import com.net.oil.base.BaseActivity;
import com.net.oil.base.EventBussMessage;
import com.net.oil.http.AppUrl;
import com.net.oil.user.bean.UserInfo;
import com.net.oil.user.contract.LoginContract;
import com.net.oil.user.presenter.LoginPresenter;
import com.net.oil.util.SharedPreferencesKey;
import com.net.oil.util.SharedPreferencesUtil;
import com.net.oil.util.StringUtil;
import com.net.oil.webview.WebViewActivity;
import com.net.oil.widget.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View {

    private static final int LoginTypePassword = 1;     //账号密码登陆
    private static final int LoginTypeAuthCode = 2;     //手机号验证码登陆

    @BindView(R.id.input_account_et)
    EditText inputAccountEt;
    @BindView(R.id.input_password_et)
    EditText inputPasswordEt;
    @BindView(R.id.forgot_password)
    TextView forgotPassword;
    @BindView(R.id.register)
    TextView register;
    @BindView(R.id.login_button)
    Button loginButton;
    @BindView(R.id.login_type_cb)
    CheckBox loginTypeCb;
    @BindView(R.id.get_verify_code_button)
    TextView getVerifyCodeButton;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.user_agreement_tv)
    TextView userAgreementTv;

    private Gson gson;
    private int loginType = LoginTypePassword;

    private long allTime = 60 * 1000;   //计时器时间
    private long stepTime = 1000;       //计时器每步的时间

    //计时器
    CountDownTimer timer = new CountDownTimer(allTime, stepTime) {
        @Override
        public void onTick(long millisUntilFinished) {
            getVerifyCodeButton.setText(String.format(getString(R.string.millis_format), millisUntilFinished / 1000));
            getVerifyCodeButton.setEnabled(false);
        }

        @Override
        public void onFinish() {
            getVerifyCodeButton.setText("重新获取验证码");
            getVerifyCodeButton.setEnabled(true);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        presenter = new LoginPresenter(this);
        gson = new Gson();
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        String phoneNumber = SharedPreferencesUtil.getStringParam(this, SharedPreferencesKey.PHONE_NUMBER, "");
        if (!TextUtils.isEmpty(phoneNumber)) {
            inputAccountEt.setText(phoneNumber);
        }
        loginTypeCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                changeLoginUi(isChecked);
            }
        });
    }

    private void changeLoginUi(boolean isChecked) {
        if (isChecked) {
            loginType = LoginTypeAuthCode;
            loginTypeCb.setText("账号密码登录");
            getVerifyCodeButton.setVisibility(View.VISIBLE);
            inputPasswordEt.setHint("请输入验证码");
        } else {
            loginType = LoginTypePassword;
            loginTypeCb.setText("短信验证码登录");
            getVerifyCodeButton.setVisibility(View.GONE);
            inputPasswordEt.setHint("请输入密码");
        }
    }

    /**
     * 获取验证码
     */
    public void getPhoneCode() {
        String phoneNumber = inputAccountEt.getText().toString();
        if (!StringUtil.isEmpty(phoneNumber)) {
            timer.start();
            presenter.getPhoneCode(phoneNumber, false);
        }
    }

    @OnClick({R.id.forgot_password, R.id.register, R.id.login_button, R.id.get_verify_code_button, R.id.user_agreement_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.forgot_password:
                startActivity(new Intent(this, ResetLoginPasswordActivity.class));
                break;
            case R.id.register:
                startActivity(new Intent(this, RegisterActivity.class));
                finish();
                break;
            case R.id.login_button:
                login();
                break;
            case R.id.get_verify_code_button:
                getPhoneCode();
                break;
            case R.id.user_agreement_tv:
                Intent intent = new Intent();
                intent.setClass(this, WebViewActivity.class);
                intent.putExtra(Constant.INTENT_TO_WEBVIEW_URL_KEY, AppUrl.ABOUS_US);
                intent.putExtra(Constant.INTENT_IS_SHARE, false);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 登陆
     */
    private void login() {
        if (!checkbox.isChecked()){
            ToastUtil.showErrorToast(this, getString(R.string.tips_user_argeement));
            return;
        }
        String accountNumber = inputAccountEt.getText().toString();
        String password = inputPasswordEt.getText().toString();

        if (!StringUtil.isEmpty(accountNumber)) {
            if (!StringUtil.isEmpty(password)) {
                showProgressDialog();
                /* 根据所选的登陆类型登陆 */
                if (loginType == LoginTypePassword) {
                    presenter.login(accountNumber, password);
                } else if (loginType == LoginTypeAuthCode) {
                    presenter.loginByAuthCode(accountNumber, password);
                }
            } else {
                /* 验证码或者密码为空 */
                if (loginType == LoginTypePassword) {
                    ToastUtil.showErrorToast(this, "请输入密码");
                } else if (loginType == LoginTypeAuthCode) {
                    ToastUtil.showErrorToast(this, "请输入验证码");
                }
            }
        } else {
            ToastUtil.showErrorToast(this, "请输入账号");
        }
    }

    /**
     * 登陆成功
     *
     * @param userInfo 返回用户信息
     */
    @Override
    public void loginSuccess(UserInfo userInfo) {
        dismissProgressDialog();
        if (userInfo != null) {
            UserInfoManager.getInstance().setUserInfo(gson.toJson(userInfo));
            ToastUtil.showSuccessToast(this, "登录成功");
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable(Constant.LOGIN_RESULT_INTENT_KEY, userInfo);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
            EventBus.getDefault().post(new EventBussMessage(Constant.LOGIN_SUCCESS_CODE, Constant.LOGIN_SUCCESS_MESSAGE));

            if (userInfo.isHasCoupon()) {
                /* 如果有优惠券未领取，则发送消息，在mainActivity中接受消息，显示领取优惠券 */
                EventBus.getDefault().post(new EventBussMessage(Constant.HAS_COUPON_CODE, Constant.HAS_COUPON_MESSAGE));
            }
            finish();
        } else {
            ToastUtil.showErrorToast(this, "登录失败");
        }
    }

    /**
     * 登陆失败
     */
    @Override
    public void loginFailed() {
        dismissProgressDialog();
    }

    /**
     * 获取验证码成功
     */
    @Override
    public void getPhoneCodeSuccess() {

    }

    /**
     * 获取验证码失败
     */
    @Override
    public void getPhoneCodeFailed() {
        timer.cancel();
        timer.onFinish();
    }

    /**
     * 通过验证码登陆成功
     *
     * @param userInfo 用户信息
     */
    @Override
    public void loginByAuthCodeSuccess(UserInfo userInfo) {
        dismissProgressDialog();
        if (userInfo != null) {

            UserInfoManager.getInstance().setUserInfo(gson.toJson(userInfo));
            ToastUtil.showSuccessToast(this, "登录成功");
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable(Constant.LOGIN_RESULT_INTENT_KEY, userInfo);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
            EventBus.getDefault().post(new EventBussMessage(Constant.LOGIN_SUCCESS_CODE, Constant.LOGIN_SUCCESS_MESSAGE));

            if (userInfo.isHasCoupon()) {
                /* 如果有优惠券未领取，则发送消息，在mainActivity中接受消息，显示领取优惠券 */
                EventBus.getDefault().post(new EventBussMessage(Constant.HAS_COUPON_CODE, Constant.HAS_COUPON_MESSAGE));
            }
            finish();
        } else {
            ToastUtil.showErrorToast(this, "登录失败");
        }
    }

    /**
     * 通过验证码登陆失败
     */
    @Override
    public void loginByAuthCodeFailed() {
        dismissProgressDialog();
    }
}
